/*
 * (C) APUE
 * Implementation of sleep()
 */
#include <signal.h>


static void sig_alrm(int signo)
{
	/* nothing to do, just returnning wakes up sigsuspend() */
}

unsigned int sleep(unsigned int nsecs)
{
	struct sigaction newact, oldact;
	sigset_t newmask, oldmask, suspmask;
	unsigned int unslept;

	/* set our handler, save previous information */
	newact.sa_handler = sig_alrm;
	sigemptyset(&newact.sa_mask);
	newact.sa_flags = 0;
	sigaction(SIGALRM, &newact, &oldact);

	/* block SIGALRM untile alarm is called, and save current signal mask */
	sigemptyset(&newmask);
	sigadd(&newmask, SIGALRM);
	sigprocmask(SIG_BLOCK, &newmask, &oldmask);

	/* alarm */
	alarm(nsecs);

	/* now unblock SIGALRM */
	suspmask = oldmask;
	sigdelset(&suspmask, SIGALRM);
	sigsuspend(&suspmask);	/* until signal interupt this */

	/* now one signal handler should be executed and return */
	/* and signal mask is set to newmask, means SIGALRM is blocked */

	unslept = alarm(0);	/* whatever, it's end of alarm() */

	/* restore information previous */
	sigaction(SIGALRM, &oldact, NULL);
	sigprocmask(SIG_SETMASK, &oldmask, NULL);
	return (unslept);
}
